<?php

namespace App\Admin\Controllers;

use App\Notifications\EmailSiteStateNotification;
use Notification;

use App\Models\Tag;
use App\Models\Area;
use App\Models\Column;
use App\Models\Site;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;

class SiteController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('网站管理');
            $content->description('列表');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('网站管理');
            $content->description('编辑');
            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('网站管理');
            $content->description('创建');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Site::class, function (Grid $grid) {

            $grid->id('ID')->sortable();

            $grid->name('网站名称');
            $grid->column('user_id','用户id');
            $grid->column('user.name','用户昵称');
            $grid->column('state','状态')->display(function ($type){
                switch ($type)
                {
                    case 1:
                        return '已审核';
                        break;
                    case 0:
                        return '审核中';
                        break;
                }
            });
            $grid->filter(function($filter){
                // 在这里添加字段过滤器
                $filter->like('name', '网站名称');
                $filter->like('url', '网站域名');
            });

            $grid->created_at('添加时间');
            $grid->disableExport(); //禁用导出数据按钮
            $grid->disableRowSelector(); //禁用行选择checkbox
            $grid->actions(function ($actions) {
                $actions->disableDelete();
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Site::class, function (Form $form) {

            $form->display('id', 'ID');

            $form->text('name','网站名称')->placeholder('请输入网站名称')->rules('required',[
                'required' => '请填写网站名称',
            ]);
            $form->text('url','网站域名')->placeholder('请输入网站域名')->rules('required',[
                'required' => '请填写网站域名',
            ]);
            $form->select('column_id','所属栏目')->options(Column::selectOptions())->placeholder('请输入所属栏目')->rules('required',[
                'required' => '请填写所属栏目',
            ]);
            $form->select('area_id','所属地区')->options(Area::all()->pluck('name', 'id'))->placeholder('请输入所属地区')->rules('required',[
                'required' => '请填写所属地区',
            ]);
            $form->tags('keywords','关键词')->placeholder('请输入关键词')->rules('required',[
                'required' => '请填写关键词',
            ]);
            $form->textarea('description','网站描述')->rows(3);

            $form->file('icon','ICO图标');

            $form->embeds('content', '设置内容', function ($form) {
                $form->ip('ip', 'IP地址');
                $form->number('alexa', '世界排名');
                $form->number('br', '百度权重');
                $form->number('mbr', '移动权重');
                $form->number('pr', '谷歌PR');
                $form->number('sbr', '搜狗PR');
            });
            $states = [
                'on'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
            ];

            $form->switch('is_best', '是否推荐')->states($states);
            $form->switch('is_top', '是否置顶')->states($states);
            $form->switch('is_pay', '是否付费')->states($states);
            $form->select('state', '状态')->options([0 => '审核中', 1 => '已审核']);

            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
            $form->saved(function (Form $form) {
                if($form->keywords) {
                    $keywords   = $this->normalizeTag(array_filter($form->keywords));
                    $site       = Site::find($form->model()->id);
                    $site->tags()->detach();
                    $site->tags()->attach($keywords);
                }
                if($form->model()->state == 1){
                    if($form->model()->user){
                        $site       = Site::find($form->model()->id);
                        Notification::send($form->model()->user, new EmailSiteStateNotification($site));
                    }
                    $this->ziyuan($form->model()->id);
                    $this->xiongzhanghao($form->model()->id);
                }
            });
        });
    }
    public function normalizeTag(array $tag)
    {
        return collect($tag)->map(function ($tag) {
            $newTag   = Tag::where('name',$tag)->first();
            if($newTag) {
                return $newTag->id;
            }else {
                $newTopic = Tag::create(['name' => $tag]);
                return $newTopic->id;
            }
        })->toArray();
    }
    function ziyuan($id)
    {
        $urls = array(
            'https://www.webshowu.com/siteinfo-'.$id.'.html',
        );
        $api = 'http://data.zz.baidu.com/urls?site=https://www.webshowu.com&token=8L1SZmj4lxFJ9fWf';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
    function xiongzhanghao($id)
    {
        $urls = array(
            'https://www.webshowu.com/siteinfo-'.$id.'.html',
        );
        $api = 'http://data.zz.baidu.com/urls?appid=1614110158395361&token=2FoJNXUZMhtpSeOV&type=realtime';
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
}
